package com.cloudinnov.logic.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.cloudinnov.dao.EquipmentPointsDao;
import com.cloudinnov.dao.HistoryDataDao;
import com.cloudinnov.dao.mongo.HistoryDataMongoDBDao;
import com.cloudinnov.logic.HistoryDataLogic;
import com.cloudinnov.model.EquipmentPoints;
import com.cloudinnov.model.HistoryData;
import com.cloudinnov.model.HistoryDataToMongoDB;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;
import com.cloudinnov.utils.PropertiesUtils;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author chengning
 * @date 2016年2月24日下午4:46:34
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Service("historyDataLogic")
public class HistoryDataLogicImpl extends BaseLogicImpl<HistoryData> implements HistoryDataLogic {
	private static final Logger logger = LoggerFactory.getLogger(HistoryDataLogicImpl.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
	private SimpleDateFormat sdfMinute = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private SimpleDateFormat realSdf = new SimpleDateFormat("yyyyMMddHH");
	private SimpleDateFormat sdfSql = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
	private SimpleDateFormat redisSdf = new SimpleDateFormat("yyyyMMddHH");
	private static final String POINT_NAME = "point:";
	private static final String VALUE_NAME = ":value";
	private static final String REALTIME_SPLITTER_LEVEL1 = ",";
	private static final int POINT_TIME_SPLITTER_LEVEL1 = 0;
	private static final int POINT_NAME_SPLITTER_LEVEL1 = 1;
	private static final int POINT_HISTORY_TIME_SPLITTER_LEVEL1 = 2;
	private static final String HISTORY_SPLITTER_LEVEL1 = ":";
	private static final String REGULAR_VALUE = "*";
	@Autowired
	private HistoryDataDao historyDataDao;
	@Autowired
	private EquipmentPointsDao equipmentPointsDao;
	@Autowired
	private JedisPool jedisPool;
	@Autowired
	private HistoryDataMongoDBDao historyDataMongoDBDao;
	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public int insertHistoryList(List<HistoryData> list, String tableName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("tableName", "history_data");
		int returnCode = historyDataDao.insertHistoryList(map);
		return returnCode;
	}
	@Override
	public int insert(Map<String, Object> map) {
		int returnCode = historyDataDao.insert(map);
		return returnCode;
	}
	/**
	 * 查询历史数据 1.开始时间和结束都在当前小时之内，查询redis历史数据 2.开始时间在当前小时之内，结束时间超过当前小时，查询redis历史数据库
	 * 3.开始时间不在当前小时，结束时间在当前小时,除去结束时间的小时数,前几个小时查询数据库,最后一个小时查询redis历史数据库 4.除以上情况以外，直接查询数据库 可能还有需要的逻辑
	 */
	@SuppressWarnings("static-access")
	@Override
	public List<List<String>> selectHistoryDatas(String code, String startTime, String endTime,
			Map<String, Object> param) {
		if (code == null || startTime == null || endTime == null) {
			return null;
		}
		Jedis redis = null;
		List<List<String>> historyList = new ArrayList<List<String>>();
		try {
			redis = jedisPool.getResource();
			Map<String, Object> map = new HashMap<String, Object>();
			// 开始时间
			Date start = null;
			// 结束时间
			Date end = null;
			try {
				start = sdfMinute.parse(startTime);
				end = sdfMinute.parse(endTime);
			} catch (ParseException e) {
				logger.error("查询历史数据日期转换异常", e);
				return historyList;
			}
			Calendar cal = Calendar.getInstance();
			cal.add(cal.HOUR_OF_DAY, 0);
			Date currentTime = cal.getTime();
			String curTime = sdf.format(currentTime);
			/**
			 * 结束时间大于当前时间，或者开始时间大于当前时间
			 */
			if (start.after(currentTime)) {
				start = currentTime;
			}
			if (end.after(currentTime)) {
				end = currentTime;
			}
			if (end.before(start)) {
				cal.setTime(start);
				cal.add(cal.HOUR_OF_DAY, 1);
				end = cal.getTime();
			}
			param.put("codes", code.split(","));
			List<EquipmentPoints> pointList = equipmentPointsDao.listByCode(param);
			for (EquipmentPoints point : pointList) {
				param.put(point.getCode(), point.getName());
			}
			/**
			 * 判断查询时间是否为当前时间 if(是当前小时) 查询redis历史list 开始和结束时间都在本小时之内 1.如果开始时间和结束时间都在当前小时之内
			 * 2.如果开始时间在本小时
			 */
			if ((sdf.format(start).equals(curTime) && sdf.format(end).equals(curTime))
					|| (sdf.format(start).equals(curTime))) {
				StringBuilder sb = null;
				String[] pointCodes = code.split(",");
				for (int i = 0; i < pointCodes.length; i++) {
					sb = new StringBuilder();
					sb.append(POINT_NAME).append(pointCodes[i] + ":").append(realSdf.format(start)).append(VALUE_NAME);
					List<String> list = redis.lrange(sb.toString(), 0, -1);
					List<String> realList = new ArrayList<String>();
					Set<String> keys = new HashSet<String>();
					if (list != null && list.size() > 0) {
						String value = null;
						String time = null;
						boolean isSuccess = false;
						for (String field : list) {
							Date date = CommonUtils
									.timeStampToDate(field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
							if (date == null) {
								continue;
							}
							if (date.after(start) && date.before(end)) {
								if (!isSuccess) {
									value = CommonUtils.strFormatTwoDecimal(
											field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""));
									time = CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
									isSuccess = true;
								} else {
									if (keys.contains(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										continue;
									}
									if (Long.parseLong(time) == Long.parseLong(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else if (CommonUtils.timeStampSubStringTen(field
											.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]) != null) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else {
										realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
									}
									time = String.valueOf(Long.parseLong(time) + 1);
								}
								keys.add(time);
							}
						}
						historyList.add(realList);
					}
				}
			}
			/**
			 * 如果开始时间不在当前小时，结束时间在当前小时
			 */
			else if (!sdf.format(start).equals(curTime) && sdf.format(end).equals(curTime)) {
				String[] codes = code.split(",");
				for (int i = 0; i < codes.length; i++) {
					List<String> realList = new ArrayList<String>();
					Set<String> keys = new HashSet<String>();
					/**
					 * 查询结束时间减去1个小时的数据库历史数据
					 */
					map.put("code", codes[i]);
					map.put("starttime", sdfSql.format(start));
					Calendar last = Calendar.getInstance();
					last.setTime(end);
					// 结束时间减去1个小时去查询数据库
					last.add(Calendar.HOUR_OF_DAY, -1);
					map.put("endtime", sdfSql.format(end.getTime()));
					List<String> values = historyDataDao.selectHistoryData(map);
					StringBuilder sb = new StringBuilder();
					if (values != null && values.size() > 0) {
						for (int k = 0; k < values.size(); k++) {
							if (k == 0) {
								sb.append(values.get(k));
							} else {
								sb.append(":" + values.get(k));
							}
						}
					}
					/**
					 * 查询剩余的当前小时的redis数据
					 */
					String[] pointCodes = code.split(",");
					StringBuilder nowSb = new StringBuilder();
					for (int j = 0; j < pointCodes.length; j++) {
						nowSb.append(POINT_NAME).append(pointCodes[j] + ":").append(realSdf.format(end))
								.append(VALUE_NAME);
						List<String> list = redis.lrange(nowSb.toString(), 0, -1);
						nowSb = new StringBuilder();
						if (list != null && list.size() > 0) {
							for (int n = 0; n < list.size(); n++) {
								if (n == 0) {
									nowSb.append(list.get(n));
								} else {
									nowSb.append(":" + list.get(n));
								}
							}
						}
					}
					if (sb.length() > 0) {
						sb.append(":" + nowSb);
					} else {
						sb.append(nowSb);
					}
					if (sb != null && sb.length() > 0) {
						String[] fields = sb.toString().split(";");
						String value = null;
						String time = null;
						boolean isSuccess = false;
						for (String field : fields) {
							Date date = CommonUtils
									.timeStampToDate(field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
							if (date == null) {
								continue;
							}
							if (date.after(start) && date.before(end)) {
								if (!isSuccess) {
									value = CommonUtils.strFormatTwoDecimal(
											field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""));
									time = CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
									isSuccess = true;
								} else {
									if (keys.contains(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										continue;
									}
									if (Long.parseLong(time) == Long.parseLong(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else if (CommonUtils.timeStampSubStringTen(field
											.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]) != null) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else {
										realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
									}
									time = String.valueOf(Long.parseLong(time) + 1);
								}
								keys.add(time);
							}
						}
						historyList.add(realList);
					}
				}
			} /**
				 * 判断是否查询为当前时间 else(不是是当前小时),查询数据库 如果开始时间和结束时间都不在本小时
				 */
			else {
				String[] codes = code.split(",");
				map.put("starttime", sdfSql.format(start));
				map.put("endtime", sdfSql.format(end));
				for (int i = 0; i < codes.length; i++) {
					List<String> realList = new ArrayList<String>();
					Set<String> keys = new HashSet<String>();
					map.put("code", codes[i]);
					List<String> values = historyDataDao.selectHistoryData(map);
					if (values == null || values.size() == 0) {
						continue;
					}
					StringBuilder sb = new StringBuilder();
					for (int k = 0; k < values.size(); k++) {
						if (k == 0) {
							sb.append(values.get(k));
						} else {
							sb.append(":" + values.get(k));
						}
					}
					String[] fields = sb.toString().split(";");
					String value = null;
					String time = null;
					boolean isSuccess = false;
					for (String field : fields) {
						Date date = CommonUtils
								.timeStampToDate(field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
						if (date == null) {
							continue;
						}
						if (date.after(start) && date.before(end)) {
							if (!isSuccess) {
								value = CommonUtils
										.strFormatTwoDecimal(field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""));
								time = CommonUtils.timeStampSubStringTen(
										field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
								isSuccess = true;
							} else {
								if (keys.contains(CommonUtils.timeStampSubStringTen(
										field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
									continue;
								}
								if (Long.parseLong(time) == Long.parseLong(CommonUtils.timeStampSubStringTen(
										field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
									realList.add(CommonUtils.strFormatTwoDecimal(
											field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
											+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(
													field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
								} else if (CommonUtils.timeStampSubStringTen(
										field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]) != null) {
									realList.add(CommonUtils.strFormatTwoDecimal(
											field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
											+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(
													field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
								} else {
									realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
								}
								time = String.valueOf(Long.parseLong(time) + 1);
							}
							keys.add(time);
						}
					}
					historyList.add(realList);
				}
			}
		} catch (Exception e) {
			logger.error("历史数据查询异常 \r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return historyList;
	}
	@Override
	public int saveDataToMongoDBByRedis() {
		HistoryDataToMongoDB model = null;
		int count = 0;
		String pointCode;
		String time;
		Calendar cal = Calendar.getInstance();
		long start = System.currentTimeMillis();
		logger.debug("----历史定时处理服务开始启动----\t" + sdfSql.format(cal.getTime()));
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			// 获取所有历史数据key
			Set<String> historykeys = redis
					.keys(POINT_NAME + REGULAR_VALUE + HISTORY_SPLITTER_LEVEL1 + REGULAR_VALUE + VALUE_NAME);
			if (historykeys != null) {
				for (String key : historykeys) {
					time = key.split(HISTORY_SPLITTER_LEVEL1)[POINT_HISTORY_TIME_SPLITTER_LEVEL1];
					Date redisKeyTime = redisSdf.parse(time);
					if (cal.getTimeInMillis() - redisKeyTime.getTime() >= 3600) {
						List<String> list = new ArrayList<String>();
						redis.select(Integer.parseInt(PropertiesUtils.findPropertiesKey("redis.db.pointvalue")));
						list = redis.lrange(key, 0, -1);
						if (list != null && list.size() > 0) {
							pointCode = key.split(HISTORY_SPLITTER_LEVEL1)[POINT_NAME_SPLITTER_LEVEL1];
							List<HistoryDataToMongoDB.Data> data = compressed(list);
							if (JudgeNullUtil.iList(data)) {
								EquipmentPoints pointModel = equipmentPointsDao
										.selectPointEquDataByPointCode(pointCode);
								if (pointModel != null) {
									model = new HistoryDataToMongoDB();
									model.setPointCode(pointCode);
									model.setTime(cal.getTime());
									model.setEquipmentCode(pointModel.getEquipmentCode());
									model.setPointName(pointModel.getName());
									model.setSectionCode(pointModel.getSectionCode());
									model.setData(data);
									historyDataMongoDBDao.save(model);
									logger.debug(
											"点位\t: " + pointCode + "入库成功\t,时间为:" + sdfMinute.format(cal.getTime()));
									count++;
								}
							}
						}
					}
				}
			}
			logger.debug("------------历史定时处理服务处理完毕---------------\t处理" + count + "条 -----共 耗时(s)"
					+ (System.currentTimeMillis() - start) / 1000);
		} catch (Exception e) {
			logger.error("saveDataToMongoDBByRedis is error, data: {}, error: {}", model, e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return count;
	}
	private List<HistoryDataToMongoDB.Data> compressed(List<String> list) {
		List<HistoryDataToMongoDB.Data> datas = new ArrayList<>();
		HistoryDataToMongoDB.Data data;
		for (int i = 0; i < list.size(); i++) {
			data = new HistoryDataToMongoDB().new Data();
			data.setValue(list.get(i).split(",")[1]);
			data.setTime(Long.parseLong(list.get(i).split(",")[0]));
			datas.add(data);
		}
		return datas;
	}
	@SuppressWarnings({ "unchecked", "deprecation" })
	private List<HistoryDataToMongoDB.Data> selectDataByMongdb(Date startTime, Date endTime, String pointCode) {
		List<HistoryDataToMongoDB.Data> datas = new ArrayList<>();
		BasicDBObject[] array = new BasicDBObject[] { new BasicDBObject("time", new BasicDBObject("$gte", startTime)),
				new BasicDBObject("time", new BasicDBObject("$lte", endTime)),
				new BasicDBObject("pointCode", pointCode) };
		BasicDBObject cond = new BasicDBObject();
		cond.put("$and", array);
		DBObject match = new BasicDBObject("$match", cond);
		AggregationOutput output = mongoTemplate.getCollection("historyDataToMongoDB").aggregate(match);
		for (DBObject dbObject : output.results()) {
			if (dbObject.get("data") != null) {
				datas.addAll((List<HistoryDataToMongoDB.Data>) dbObject.get("data"));
			}
		}
		return datas;
	}
	@Override
	public List<List<String>> selectHistoryDatasByMongoDB(String code, String startTime, String endTime,
			Map<String, Object> param) {
		if (code == null || startTime == null || endTime == null) {
			return null;
		}
		Jedis redis = null;
		List<List<String>> historyList = new ArrayList<List<String>>();
		try {
			redis = jedisPool.getResource();
			// 开始时间
			Date start = null;
			// 结束时间
			Date end = null;
			try {
				start = sdfMinute.parse(startTime);
				end = sdfMinute.parse(endTime);
			} catch (ParseException e) {
				logger.error("查询历史数据日期转换异常", e);
				return historyList;
			}
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.HOUR_OF_DAY, 0);
			Date currentTime = cal.getTime();
			String curTime = sdf.format(currentTime);
			/**
			 * 结束时间大于当前时间，或者开始时间大于当前时间
			 */
			if (start.after(currentTime)) {
				start = currentTime;
			}
			if (end.after(currentTime)) {
				end = currentTime;
			}
			if (end.before(start)) {
				cal.setTime(start);
				cal.add(Calendar.HOUR_OF_DAY, 1);
				end = cal.getTime();
			}
			param.put("codes", code.split(","));
			List<EquipmentPoints> pointList = equipmentPointsDao.listByCode(param);
			for (EquipmentPoints point : pointList) {
				param.put(point.getCode(), point.getName());
			}
			/**
			 * 判断查询时间是否为当前时间 if(是当前小时) 查询redis历史list 开始和结束时间都在本小时之内 1.如果开始时间和结束时间都在当前小时之内
			 * 2.如果开始时间在本小时
			 */
			if ((sdf.format(start).equals(curTime) && sdf.format(end).equals(curTime))
					|| (sdf.format(start).equals(curTime))) {
				StringBuilder sb = null;
				String[] pointCodes = code.split(",");
				for (int i = 0; i < pointCodes.length; i++) {
					sb = new StringBuilder();
					sb.append(POINT_NAME).append(pointCodes[i] + ":").append(realSdf.format(start)).append(VALUE_NAME);
					List<String> list = redis.lrange(sb.toString(), 0, -1);
					List<String> realList = new ArrayList<String>();
					Set<String> keys = new HashSet<String>();
					if (list != null && list.size() > 0) {
						String value = null;
						String time = null;
						boolean isSuccess = false;
						for (String field : list) {
							Date date = CommonUtils
									.timeStampToDate(field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
							if (date == null) {
								continue;
							}
							if (date.after(start) && date.before(end)) {
								if (!isSuccess) {
									value = CommonUtils.strFormatTwoDecimal(
											field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""));
									time = CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]);
									isSuccess = true;
								} else {
									if (keys.contains(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										continue;
									}
									if (Long.parseLong(time) == Long.parseLong(CommonUtils.timeStampSubStringTen(
											field.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]))) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else if (CommonUtils.timeStampSubStringTen(field
											.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]) != null) {
										realList.add(CommonUtils.strFormatTwoDecimal(
												field.split(REALTIME_SPLITTER_LEVEL1)[1].replace(" ", ""))
												+ REALTIME_SPLITTER_LEVEL1 + CommonUtils.timeStampSubStringTen(field
														.split(REALTIME_SPLITTER_LEVEL1)[POINT_TIME_SPLITTER_LEVEL1]));
									} else {
										realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
									}
									time = String.valueOf(Long.parseLong(time) + 1);
								}
								keys.add(time);
							}
						}
						historyList.add(realList);
					}
				}
			} else if (!sdf.format(start).equals(curTime) && sdf.format(end).equals(curTime)) {// 如果开始时间不在当前小时，结束时间在当前小时
				String[] codes = code.split(",");
				for (int i = 0; i < codes.length; i++) {
					List<String> realList = new ArrayList<String>();
					Set<Long> keys = new HashSet<Long>();
					/**
					 * 查询结束时间减去1个小时的数据库历史数据
					 */
					Calendar last = Calendar.getInstance();
					last.setTime(end);
					// 结束时间减去1个小时去查询数据库
					last.add(Calendar.HOUR_OF_DAY, -1);
					List<HistoryDataToMongoDB.Data> datas = selectDataByMongdb(start, end, codes[i]);
					if (!JudgeNullUtil.iList(datas)) {
						datas = new ArrayList<>();
					}
					/**
					 * 查询剩余的当前小时的redis数据
					 */
					String redisKey = POINT_NAME + code + ":" + realSdf.format(end) + VALUE_NAME;
					List<String> list = redis.lrange(redisKey, 0, -1);
					if (list != null && list.size() > 0) {
						HistoryDataToMongoDB.Data redisData = null;
						for (int n = 0; n < list.size(); n++) {
							redisData = new HistoryDataToMongoDB().new Data();
							redisData.setTime(Long.parseLong(list.get(i).split(REALTIME_SPLITTER_LEVEL1)[0]));
							redisData.setValue(list.get(i).split(REALTIME_SPLITTER_LEVEL1)[1]);
							datas.add(redisData);
						}
					}
					if (JudgeNullUtil.iList(datas)) {
						Object value = null;
						long time = 0;
						boolean isSuccess = false;
						for (HistoryDataToMongoDB.Data field : datas) {
							Date date = CommonUtils.timeStampToDate(field.getTime());
							if (date == null) {
								continue;
							}
							if (date.after(start) && date.before(end)) {
								if (!isSuccess) {
									value = field.getValue();
									time = field.getTime();
									isSuccess = true;
								} else {
									if (keys.contains(field.getTime())) {
										continue;
									}
									if (time == field.getTime()) {
										realList.add(field.getValue() + REALTIME_SPLITTER_LEVEL1 + field.getTime());
									} else if (field.getTime() != null) {
										realList.add(field.getValue() + REALTIME_SPLITTER_LEVEL1 + field.getTime());
									} else {
										realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
									}
									time = time + 1;
								}
								keys.add(time);
							}
						}
						historyList.add(realList);
					}
				}
			} else {// 判断是否查询为当前时间 else(不是是当前小时),查询数据库 如果开始时间和结束时间都不在本小时
				String[] codes = code.split(",");
				for (int i = 0; i < codes.length; i++) {
					List<String> realList = new ArrayList<String>();
					Set<Long> keys = new HashSet<Long>();
					/**
					 * 查询结束时间减去1个小时的数据库历史数据
					 */
					Calendar last = Calendar.getInstance();
					last.setTime(end);
					// 结束时间减去1个小时去查询数据库
					last.add(Calendar.HOUR_OF_DAY, -1);
					List<HistoryDataToMongoDB.Data> datas = selectDataByMongdb(start, end, codes[i]);
					if (!JudgeNullUtil.iList(datas)) {
						datas = new ArrayList<>();
					}
					if (JudgeNullUtil.iList(datas)) {
						Object value = null;
						long time = 0;
						boolean isSuccess = false;
						for (HistoryDataToMongoDB.Data field : datas) {
							Date date = CommonUtils.timeStampToDate(field.getTime());
							if (date == null) {
								continue;
							}
							if (date.after(start) && date.before(end)) {
								if (!isSuccess) {
									value = field.getValue();
									time = field.getTime();
									isSuccess = true;
								} else {
									if (keys.contains(field.getTime())) {
										continue;
									}
									if (time == field.getTime()) {
										realList.add(field.getValue() + REALTIME_SPLITTER_LEVEL1 + field.getTime());
									} else if (field.getTime() != null) {
										realList.add(field.getValue() + REALTIME_SPLITTER_LEVEL1 + field.getTime());
									} else {
										realList.add(value + REALTIME_SPLITTER_LEVEL1 + time);
									}
									time = time + 1;
								}
								keys.add(time);
							}
						}
						historyList.add(realList);
					}
				}
			}
		} catch (Exception e) {
			logger.error("历史数据查询异常 \r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return historyList;
	}
}
